package Tool;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Random;

public class Tool {
	public static void writeString(String str, OutputStream out) throws IOException{
		byte[] buf = str.getBytes();
		out.write(int2bytes(buf.length, new byte[4], 0));
		out.write(buf);
	}
	
	public static String readString(InputStream in) throws IOException{
		byte[] buf = new byte[4];
		in.read(buf);
		buf = new byte[bytes2int(buf, 0)];
		in.read(buf);
		String ret = new String(buf);
		return ret;
	}
	
	public static byte[] int2bytes(int in, byte[] ret, int off){
		for (int i = 3+off; i >= off; in >>= 8)
			ret[i--] = (byte)in;
		return ret;
	}
	public static int bytes2int(byte[] bs, int off){
		int ret = 0;
		for (int i = off; i < off + 4; ++i){
			ret = (ret << 8) + (bs[i]&0xff);
		}
		return ret;
	}
	
	public static InputStream getInputStream(Binaryable bi) throws IOException{
		InputStream in = null;
		Random rand = new Random();
		File temp = File.createTempFile(Long.toString(rand.nextLong()), Long.toString(rand.nextLong()));
		OutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
		bi.toBytes(out);
		out.flush();
		in = new BufferedInputStream(new FileInputStream(temp));
		return in;
	}
	
	public static void writeInt(int in, OutputStream out) throws IOException{
		out.write(int2bytes(in, new byte[4], 0));
	}
	
	public static int readInt(InputStream in) throws IOException{
		byte[] buf = new byte[4];
		in.read(buf);
		return bytes2int(buf, 0);
	}
	
	/**
	 * 得到一个数组的迭代器
	 */
	public static<T> Iterator<T> getIterator(final T[] arr){
		return new Iterator<T>() {
			int ip = 0;
			public boolean hasNext() {return ip < arr.length;}
			public T next() {return arr[ip++];}
			public void remove() {++ip;}
		};
	}
	
	/**
	 * 把正常文本转成html格式
	 */
	public static String toHTML(String str){
		StringBuilder builder = new StringBuilder();
		char arr[] = str.toCharArray();
		for (char c : arr){
			switch (c){
			case '\'':
				builder.append("&#039;");
				break;
			case '"':
				builder.append("&quot;");
				break;
			case '&':
				builder.append("&amp;");
				break;
			case '<':
				builder.append("&lt;");
				break;
			case '>':
				builder.append("&gt;");
				break;
			case ' ':
				builder.append("&nbsp;");
				break;
			case '\t':
				builder.append("&nbsp;&nbsp;");
			case '\n':
				builder.append("<br/>");
			default:
				builder.append(c);
			}
		}
		
		return builder.toString();
	}
}






